import utils from './utils'
const crypto = require('crypto')

import { post } from 'request'
import { wx_api_key, wx_mchid, wx_serial_no } from 'src/setting';


class Token{
  constructor(){

  }

  //解密函数
  decode(params) {
    const AUTH_KEY_LENGTH = 16;
    // ciphertext = 密文，associated_data = 填充内容， nonce = 位移
    const { ciphertext, associated_data, nonce } = params;
    // 密钥
    const key_bytes = Buffer.from(wx_api_key, 'utf8');
    // 位移
    const nonce_bytes = Buffer.from(nonce, 'utf8');
    // 填充内容
    const associated_data_bytes = Buffer.from(associated_data, 'utf8');
    // 密文Buffer
    const ciphertext_bytes = Buffer.from(ciphertext, 'base64');
    // 计算减去16位长度
    const cipherdata_length = ciphertext_bytes.length - AUTH_KEY_LENGTH;
    // upodata
    const cipherdata_bytes = ciphertext_bytes.slice(0, cipherdata_length);
    // tag
    const auth_tag_bytes = ciphertext_bytes.slice(cipherdata_length, ciphertext_bytes.length);
    const decipher = crypto.createDecipheriv(
        'aes-256-gcm', key_bytes, nonce_bytes
    );
    decipher.setAuthTag(auth_tag_bytes);
    decipher.setAAD(Buffer.from(associated_data_bytes));


    const output = Buffer.concat([
        decipher.update(cipherdata_bytes),
        decipher.final(),
    ]);
    return output.toString("utf-8");
  }

  transfer(mchid,serial_no, privateKey, body, method?: string) {
  let randomStr = `${utils.randomString(32)}`;
    let time = parseInt((new Date().getTime() / 1000).toString()) + 100
    let signStr = `POST\n${method || "/v3/pay/transactions/jsapi"}\n${time}\n${randomStr}\n${JSON.stringify(body)}\n`;
    console.log(signStr,'signStr')
    // 生成签名
    let sign = crypto.createSign("RSA-SHA256");
    sign.update(signStr);
    let signed = sign.sign(privateKey, "base64");

    let signInfo = `mchid="${mchid || wx_mchid}",nonce_str="${randomStr}",signature="${signed}",timestamp="${time}",serial_no="${serial_no || wx_serial_no}"`;
    return {signInfo,timestamp:time,nonceStr:randomStr}
  }

  paySign(appid, privateKey, packageid, randomStr, time ){
    let signStr = `${appid}\n${time}\n${randomStr}\n${packageid}\n`
    // 生成签名
    let sign = crypto.createSign("RSA-SHA256");
    sign.update(signStr);
    let signed = sign.sign(privateKey, "base64");
    return {paySign:signed,timeStamp:time,nonceStr:randomStr}
  }
}

export default new Token()
